package com.lineage.server.timecontroller.pc;

import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_Poison;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.thread.PcOtherThreadPool;
import com.lineage.server.world.World;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BreakdownTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(BreakdownTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  private int _timeMillis;
  
  private Random _random;
  
  public void start(int timeMillis, Random random) {
    this._timeMillis = timeMillis;
    this._random = random;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, timeMillis, timeMillis);
  }
  
  public void run() {
    try {
      Collection all = World.get().getAllPlayers();
      if (all.isEmpty())
        return; 
      Iterator<L1PcInstance> iter = all.iterator();
      while (iter.hasNext()) {
        L1PcInstance tgpc = iter.next();
        if (this._random != null) {
          int gfxid = this._random.nextInt(3);
          tgpc.sendPackets((ServerBasePacket)new S_Poison(tgpc.getId(), gfxid));
          tgpc.broadcastPacketAll((ServerBasePacket)new S_Poison(tgpc.getId(), gfxid));
          continue;
        } 
        tgpc.sendPackets((ServerBasePacket)new S_Poison(tgpc.getId(), 0));
        tgpc.broadcastPacketAll((ServerBasePacket)new S_Poison(tgpc.getId(), 0));
      } 
    } catch (Exception e) {
      _log.error("时间轴异常重启.时间轴异常重启.时间轴异常重启", e);
      PcOtherThreadPool.get().cancel(this._timer, false);
      BreakdownTimer breakdownTimer = new BreakdownTimer();
      breakdownTimer.start(this._timeMillis, this._random);
    } 
  }
}
